<?php
namespace control;

/*
*住宿费用统计类
*/

class dormitoryFeeStatisticsClass extends adIndexClass
{
    private const page = 'dormitoryFeeStatistics';
    private const title = '住宿费用统计';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'month'          => [
                        'name'  => '月份',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'staffId' => [
                        'name'  => "入住人姓名",
                        'width' => 150,
                    ],
                    'deptName'  => [
                        'name'  => "入住人部门",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'building'         => [
                        'name'  => '楼号',
                        'width' => 100,
                    ],
                    'floor'          => [
                        'name'  => '楼层',
                        'width' => 100,
                    ],
                    'room'          => [
                        'name'  => "宿舍号",
                        'width' => 100,
                    ],
                    'day'          => [
                        'name'  => "入住天数",
                        'width' => 100,
                    ],
                    'rent'          => [
                        'name'  => "月租(".static::$unit.")",
                        'width' => 100,
                    ],
                    'electricityFee'          => [
                        'name'  => "电费(".static::$unit.")",
                        'width' => 100,
                    ],
                    'waterFee'          => [
                        'name'  => "水费(".static::$unit.")",
                        'width' => 100,
                    ],
                    'gasFee'          => [
                        'name'  => "燃气费(".static::$unit.")",
                        'width' => 100,
                    ],
                    'propertyFee'          => [
                        'name'  => "物业费(".static::$unit.")",
                        'width' => 100,
                    ],
                    'otherFee'          => [
                        'name'  => '其他费用('.static::$unit.')',
                        'width' => 100,
                    ],
                    'total'          => [
                        'name'  => '合计('.static::$unit.')',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "入住人" => selectMultiple(["name" => "staffId", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    "入住人部门"     => text(array("name" => "deptName")),
                    '楼号' => repeatSelect(array('change'=>'getFloor','sqlForm'=>"dormitory where state ='启用'",'sqlField'=>'building','name'=>'building')),
                ],
                [
                    '楼层'   => repeatSelect(array('change'=>'getRoom','sqlForm'=>"dormitory where state ='启用' and building = ''",'sqlField'=>'floor','name'=>'floor')),
                    "宿舍号" => idSelect(array('change'=>'getPeople','sqlForm'=>"dormitory where state ='启用' and building = '' and floor = ''",'sqlField'=>'room','sqlId'=>'id','name'=>'dormitoryId')),
                    '月份'   => text(array("name" => "creatTime", 'laydate' => ['type' => 'month', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $obj = new dormitoryRecordClass();
        //生成查询表单
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button)).$obj->editJs();
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            'b.deptName'=>$this->post('deptName')
        );
        //全等查询数组
        $equal = array(
            "b.staffId" => $this->post('staffId'),//入住人
            "a.dormitoryId" => $this->post('dormitoryId'),
        );
        $and = " and if(b.state='入住',date_format(b.recordDate,'%Y-%m') <= a.month,date_format(b.recordDate,'%Y-%m') <= a.month and date_format(b.outDate,'%Y-%m') >= a.month)";
        $mAnd = '';
        if (empty($this->post('dormitoryId'))){
            if ($this->post('building')){
                $mAnd.=" and building = '".$this->post('building')."'";
            }
            if ($this->post('floor')){
                $mAnd.=" and floor = '".$this->post('floor')."'";
            }
            $and.=$mAnd?" and a.dormitoryId in (select id from dormitory where 1=1 {$mAnd})":'';
        }

        if ($this->post('creatTime')) {
            $arr = explode('~', $this->post('creatTime'));
            $arr[0] = trim($arr[0]);
            $arr[1]   = trim(end($arr));
            $and .=" and a.month >= '$arr[0]' and a.month <='$arr[1]'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and." group by a.month,b.staffId,a.dormitoryId";
        $page = $this->page(array(
            'field'=>"a.month,b.staffId,a.dormitoryId,any_value(a.id) as id,any_value(b.deptName) as deptName",
            "table" => " dormitory_fee_record as a left join dormitory_record as b on a.dormitoryId = b.dormitoryId",
            "where" => $where,
            'order'=>$orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $info = query('dormitory_fee_record', " id = '$array[id]'");
            $dormitory = query('dormitory', " id = '$array[dormitoryId]'");
            //入住天数
            $day = $this->monthTotalLiveDay($array['month'], $dormitory['id'], $array['staffId']);
            //总天数
            $dayTotal = $this->monthTotalLiveDay($array['month'], $dormitory['id']);
            $total = $info['electricityFee']+$info['waterFee']+$info['gasFee']+$info['propertyFee']+$info['otherFee']+$dormitory['rent'];
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "building":
                    case "floor":
                    case "room":
                        $row[] = $dormitory[$key];
                        break;
                    case "day":
                        $row[] = $day;
                        break;
                    case "rent":
                        $row[] = $this->moneyFormat($day, $dayTotal, $dormitory['rent']);
                        break;
                    case "electricityFee":
                        $row[] = $this->moneyFormat($day, $dayTotal, $info['electricityFee']);
                        break;
                    case "waterFee":
                        $row[] = $this->moneyFormat($day, $dayTotal, $info['waterFee']);
                        break;
                    case "gasFee":
                        $row[] = $this->moneyFormat($day, $dayTotal, $info['gasFee']);
                        break;
                    case "propertyFee":
                        $row[] = $this->moneyFormat($day, $dayTotal, $info['propertyFee']);
                        break;
                    case "otherFee":
                        $row[] = $this->moneyFormat($day, $dayTotal, $info['otherFee']);
                        break;
                    case "total":
                        $row[] = $this->moneyFormat($day, $dayTotal, $total);
                        break;
                    case "staffId":
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     *
     * @param $day
     * @param $total
     * @param $money
     * @return float|int
     */
    public function moneyFormat($day, $total, $money)
    {
        $price = 0;
        if ($total >0) {
            $price = round($money/$total*$day, 2);
        }
        return $price;
    }

    /**
     * 当月当前宿舍所有人入住天数总和
     */
    public function monthTotalLiveDay($month, $dormitoryId, $stid = '')
    {
        $where = '';
        if (!empty($stid)) {
            $where = " and staffId = '$stid'";
        }
        $dayTotal = 0;
        $monthStartDate = $month.'-01';
        $monthEndDate = $month.'-'.date('t', strtotime($month));
        $result = find(array('table'=>'dormitory_record','where'=>" dormitoryId = '$dormitoryId' and if(state='入住',date_format(recordDate,'%Y-%m') <= '$month',date_format(recordDate,'%Y-%m') <= '$month' and date_format(outDate,'%Y-%m') >= '$month') {$where}"));
        foreach ($result['array'] as $array) {
            if (strtotime($array['recordDate']) < strtotime($monthStartDate)) {
                $array['recordDate'] =$monthStartDate;
            }
            if ($array['state'] =='入住') {
                if (time() > strtotime($monthEndDate)) {
                    //查看上月，截止到上月月底
                    $array['outDate'] = $monthEndDate;
                } else {
                    //当月查看 截止到当前日入住天数
                    $array['outDate'] = $this->date;
                }
            } elseif (strtotime($array['outDate']) > strtotime($monthEndDate)) {
                $array['outDate'] = $monthEndDate;
            }

            $dayTotal+= dormitoryFeeStatisticsClass::diffBetweenTwoDays($array['recordDate'], $array['outDate']);
        }
        return $dayTotal;
    }

    //获取两个日期之间相差天数
    public static function diffBetweenTwoDays($day1, $day2): float|int
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400+1;
    }

    /**
     * 计算天数
     * @param $array
     * @return int|mixed
     */
    public function days($array)
    {
        $day = 1;
        //入住天数
        $result = find(array('table'=>'dormitory_record','where'=>" date_format(recordDate,'%Y-%m') = '$array[month]' and building = '$array[building]' and room = '$array[room]' and staffId = '$array[staffId]'",'field'=>" if(state='入住',TIMESTAMPDIFF(DAY,recordDate,DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%S')),TIMESTAMPDIFF(DAY,recordDate,outDate)) as day"));
        if ($result['array']) {
            foreach ($result['array'] as $val) {
                $day+=$val['day'];
            }
        }
        return $day;
    }
    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = array('月份','入住人姓名','入住人部门',"楼号","楼层", "宿舍号","入住天数","月租(".static::$unit.")", "电费(".static::$unit.")", "水费(".static::$unit.")", "燃气费(".static::$unit.")", "物业费(".static::$unit.")",'其他费用('.static::$unit.')','合计('.static::$unit.')');
            $result = sqlFind($sql);
            if (is_array($result['array'])) {
                foreach ($result['array'] as $array) {
                    $info = query('dormitory_fee_record', " id = '$array[id]'");
                    $staff = query('staff', " stid = '$array[staffId]'");
                    $dormitory = query('dormitory', " id = '$array[dormitoryId]'");

                    $total = $info['electricityFee']+$info['waterFee']+$info['gasFee']+$info['propertyFee']+$info['otherFee']+$dormitory['rent'];
                    //入住天数
                    $day = $this->monthTotalLiveDay($array['month'], $dormitory['id'], $array['staffId']);
                    //总天数
                    $dayTotal = $this->monthTotalLiveDay($array['month'], $dormitory['id']);

                    $data[] = array($array['month'],$staff['name'], $array['deptName'], $dormitory['building'],$dormitory['floor'], $dormitory['room'],$day,$this->moneyFormat($day, $dayTotal, $dormitory['rent']), $this->moneyFormat($day, $dayTotal, $info['electricityFee']), $this->moneyFormat($day, $dayTotal, $info['waterFee']),
                        $this->moneyFormat($day, $dayTotal, $info['gasFee']),$this->moneyFormat($day, $dayTotal, $info['propertyFee']),$this->moneyFormat($day, $dayTotal, $info['otherFee']),$this->moneyFormat($day, $dayTotal, $total));
                }
            }
            $text = $this->control['name'] . "导出了住宿费用统计";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "住宿费用统计.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
